<template>
  <div class="box">
    <div class="search">
      <SearchForm :formInputs="state.formInputs" @submit="search" />
      <a-space>
        <a-button
          type="primary"
          @click="
            () => {
              state.showFactor = true;
            }
          "
        >
          <template #icon> <ci-outlined /></template>因子指标</a-button
        >

        <a-button
          type="primary"
          @click="submit"
          v-if="state.factory !== companys['3']"
        >
          <template #icon> <cloud-upload-outlined /> </template
          >数据提交</a-button
        >
        <a-button type="link" @click="downloadTemplate">
          <template #icon>
            <download-outlined />
          </template>
          下载模板
        </a-button>
        <a-upload
          :showUploadList="false"
          accept=".xls,.xlsx"
          :customRequest="
            ({ file }) => {
              uploadExcel(file);
            }
          "
          :disabled="disabled"
        >
          <a-button type="link" :disabled="disabled">
            <upload-outlined></upload-outlined>
            上传
          </a-button>
        </a-upload>
      </a-space>
    </div>
    <div class="table">
      <Monitor
        v-if="state.type === 1"
        :title="state.title"
        v-model:source="state.list"
        :edit="state.factory !== companys['3'] ? true : false"
        :ri="state.ri"
        :ri_a="state.ri_a"
      />
      <Verify
        v-if="state.type === 2"
        :title="state.title"
        :quota="state.quota"
        v-model:source="state.list"
        :edit="state.factory !== companys['3'] ? true : false"
      />
    </div>
  </div>
  <a-modal
    title="因子指标"
    v-model:visible="state.showFactor"
    :width="900"
    centered
    :destroyOnClose="true"
    :footer="null"
  >
    <Factor @onChange="factorChange" />
  </a-modal>

</template>
<script setup>
import {
  getCurrentInstance,
  reactive,
  ref,
  onMounted,
  toRaw,
  watchEffect,
} from "vue";
import SearchForm from "@/components/SearchForm.vue";
import dayjs from "dayjs";
import Monitor from "./Emission/monitor.vue";
import Verify from "./Emission/verify.vue";
import Factor from "./Emission/factor.vue";
import UploadExcel from "../components/UploadFile.vue"
import UploadFile from "../components/UploadFile.vue"
import { tmp, companys, factorCategory, categorys } from "@/utils/source";
import _ from "lodash";

const year = dayjs().year();
const yearOpts = [];
for (let i = 0; i < 20; i++) {
  const _year = year - i;
  yearOpts.push({ label: `${_year}年`, value: _year });
}

const { proxy } = getCurrentInstance();

const downloadTemplate = () => {
  console.log("state.type",state.type)
  const type = state.type
  // 后端接口地址（相对路径）
  const url = `http://localhost:8082/api/excel/import/energy?type=${type}`;

  // 创建临时 a 标签
  const link = document.createElement("a");
  link.href = url; // 直接使用相对路径，由 axios baseURL 或 Nginx 处理
  link.download = "能源数据导入模板.xlsx"; // 指定下载的文件名
  link.style.display = "none";

  // 添加到 DOM 并触发点击
  document.body.appendChild(link);
  link.click();

  // 移除元素
  document.body.removeChild(link);
};

const uploadExcel = async (file) => {
  // 1. 文件校验（可选）
  const isExcel =
    file.type === "application/vnd.ms-excel" ||
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

  if (!isExcel) {
    proxy.$message.error("只能上传 Excel 文件（.xls 或 .xlsx）!");
    return false;
  }

  // 限制文件大小（例如 10MB）
  const maxSize = 10 * 1024 * 1024; // 10MB
  if (file.size > maxSize) {
    proxy.$message.error("文件大小不能超过 10MB！");
    return false;
  }

  // 2. 构建 FormData
  const formData = new FormData();
  formData.append("file", file);
  formData.append("company", state.factory); 
  formData.append("type",state.type)
  formData.append("year", state.year);

  try {
    // 3. 调用上传接口
    const { success, msg, data } = await proxy.$axios.post(
      "/excel/import/energy", // 后端上传接口路径
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
        // 可选：显示上传进度
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          console.log(`上传进度: ${percentCompleted}%`);
          // 可结合 a-upload 的 fileItem.status 实现进度条
        },
      }
    );

    // 4. 处理响应
    if (success) {
      proxy.$message.success("文件上传成功！");
      // 上传成功后刷新数据
      search({ factory: state.factory, type: state.type, year: state.year });
    } else {
      proxy.$message.error(msg || "上传失败，请检查文件内容");
    }
  } catch (error) {
    console.error("上传出错：", error);
    proxy.$message.error("文件上传失败，请稍后重试");
  }
};


const state = reactive({
  formInputs: [
    {
      label: "船厂",
      type: "select",
      name: "factory",
      options: _.map(companys, (v, k) => ({ label: v, value: v })),
      defaultValue: companys["1"],
    },
    {
      label: "类别",
      type: "select",
      name: "type",
      options: [
        { label: "集团内部", value: 1 },
        { label: "政府核查", value: 2 },
      ],
      defaultValue: 1,
    },
    {
      label: "年份",
      type: "select",
      name: "year",
      options: yearOpts,
      defaultValue: year,
    },
  ],
  factory: null,
  type: 1,
  year,
  title: null,
  list: [],
  showFactor: false,
  factors: [], // 配置因子表
  quota: 0,
  ri: 0, //碳排放量月度/年度指标
  ri_a: 0, // 碳排放强度月度/年度指标
});

// 查询月度数据
const search = async ({ factory, type, year }) => {
  state.factory = factory;
  state.type = type;
  state.year = year;

  let list = [];
  // 动态获取数据，真实接口时替代
  const source = tmp;
  if (source) {
    state.title = factory;
    if (type === 1) {
      list = source.monitor;
    } else if (type === 2) {
      list = source.verify;
      // 招商重工没有某些能源分类
      if (factory === companys["2"]) {
        list = _.filter(
          list,
          (o) => ![categorys[11], categorys[12], categorys[13]].includes(o.name)
        );
      }
    }
  }

  // 获取因子指标中因子
  await getFactors();

  const { success, data } = await proxy.$axios.get("/energy_monitor/list", {
    params: { company: factory, year, type },
  });
  if (success && data.length) {
    list = data;
  }

  _.each(list, (o) => {
    const the = _.find(state.factors, { name: o.name, year });
    if (the) {
      o.factor = the.value;
    } else {
      o.factor = 0;
    }
  });
  state.list = list;
};

// 获取深圳配置因子
const getFactors = async () => {
  // 获取因子指标中因子
  const r = await proxy.$axios.get("/config/list");
  if (r.success) {
    const factors = r.data;
    state.factors = factors;

    const one = _.find(factors, {
      name: `${state.factory}-深圳市碳配额`,
      year: state.year,
    });
    if (one) {
      state.quota = one.value;
    } else {
      state.quota = 0;
    }

    const one1 = _.find(factors, {
      name: factorCategory[14],
      year: state.year,
    });
    if (one1) {
      state.ri = one1.value;
    } else {
      state.ri = 0;
    }

    const one2 = _.find(factors, {
      name: factorCategory[15],
      year: state.year,
    });
    if (one2) {
      state.ri_a = one2.value;
    } else {
      state.ri_a = 0;
    }
  } else {
    state.factors = [];
    state.quota = 0;
    state.ri = 0;
    state.ri_a = 0;
  }
};

onMounted(() => {
  search({ factory: companys["1"], type: 1, year });
});

const submit = () => {
  const list = toRaw(state.list);
  const array = _.filter(list, (o) => o.name != "总产值");
  const result = [];
  _.each(array, (o) => {
    const months = _.map(o.months, (month) => {
      return month * o.factor * o.ratio;
    });
    result.push({ name: o.name, months });
  });

  const months = _.map(result[0].months, (o, index) => {
    const total = _.sum(_.map(result, (obj) => obj.months[index]));
    return total;
  });
  result.push({ name: "碳排放量(因子指标)(t)", months });

  const data = {
    company: state.factory,
    type: state.type,
    year: state.year,
    list,
    result,
  };

  proxy.$axios.post("/energy_monitor", data).then(({ success, msg }) => {
    if (success) {
      proxy.$message.success("提交成功");
    }
  });
};

// 监听因子表数据变化
const factorChange = () => {
  // 月度数据重新查询
  search({ factory: state.factory, type: state.type, year: state.year });
};
</script>
<style lang="less" scoped>
.box {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px;

  .search {
    padding: 10px;
    display: flex;
    justify-content: space-between;
  }

  .table {
    flex: 1;
    padding: 2px;
    overflow: hidden;
    overflow-y: auto;
  }
}
</style>
